package cn.practice.chat.feign.api;

import cn.practice.chat.entity.ChatGroupUser;
import cn.practice.chat.entity.ChatRecord;
import cn.practice.chat.feign.service.RecordFeign;
import cn.practice.chat.lang.RedisConst;
import cn.practice.chat.lang.Result;
import cn.practice.chat.mapper.ChatGroupUserMapper;
import cn.practice.chat.mapper.ChatListMapper;
import cn.practice.chat.mapper.UserFriendMapper;
import cn.practice.chat.response.chat.ChatListResponse;
import cn.practice.chat.response.chat.ChatRecordResponse;
import cn.practice.chat.response.chat.GroupUserResponse;
import cn.practice.chat.response.message.MessageRecord;
import cn.practice.chat.service.ChatRecordService;
import cn.practice.chat.utils.RedisUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @ClassName RecordFeignImpl
 * @Description:
 * @Author A-TAO
 * @Date 2022/11/1
 * @Version V1.0
 **/

@Slf4j
@RestController
public class RecordFeignImpl implements RecordFeign {

    @Autowired
    private ChatRecordService chatRecordService;


    String key = RedisConst.CHAT_LIST_KEY;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ChatListMapper chatListMapper;

    @Autowired
    private ChatGroupUserMapper chatGroupUserMapper;


    @Override
    public Result addRecord(MessageRecord record) {
        // 保存数据库
        ChatRecord chatRecord = new ChatRecord();
        chatRecord.setMessageId(record.getMessageId());
        chatRecord.setMessageContent(record.getContent());
        chatRecord.setSenderId(record.getUserId());
        chatRecord.setReceiverId(record.getFriendId());
        chatRecord.setSendTime(LocalDateTime.now());
        chatRecordService.save(chatRecord);
        // 更新缓存
        String ukey = RedisConst.CHAT_LIST_KEY + record.getUserId();
        String fkey = RedisConst.CHAT_LIST_KEY + record.getFriendId();
        setChache(record.getUserId(), ukey);
        setChache(record.getFriendId(), fkey);
        return Result.success();
    }

    @Override
    public Result<List<GroupUserResponse>> getGroupUserIds(Integer groupId) {

        List<GroupUserResponse> groupUsers = chatGroupUserMapper.selectGroupUsers(groupId);

        return Result.success(groupUsers);
    }


    private void setChache(Integer userId, String key){
        // 查询最近联系人列表
        List<ChatListResponse> responseList =  chatListMapper.chatList(userId);
        log.info("获取聊天列表，responseList={}", responseList);
        if(!CollectionUtils.isEmpty(responseList)){
            // 查询聊天记录 进行封装
            List<String> messageIds = responseList.stream().map(v->v.getMessageId()).collect(Collectors.toList());
            List<ChatRecordResponse> chatRecordList = chatListMapper.recordListByMessageIdList(messageIds);
            log.info("获取聊天记录，总数量={}", chatRecordList.size());
            if(!CollectionUtils.isEmpty(chatRecordList)){
                // 判断是不是自己发的消息
                for(ChatRecordResponse record:chatRecordList){
                    if(userId.equals(record.getSenderId())){
                        record.setSelf(Boolean.TRUE);
                    }else{
                        record.setSelf(Boolean.FALSE);
                    }
                }
                List<ChatRecordResponse> childrenList = null;
                for(ChatListResponse chatResponse : responseList){
                    String msgId = chatResponse.getMessageId();
                    childrenList = chatRecordList.stream().filter(c->msgId.equals(c.getMessageId()))
                            .collect(Collectors.toList());
                    if(!CollectionUtils.isEmpty(childrenList)){
                        chatResponse.setChatRecordList(childrenList);
                    }
                }
            }
            // 缓存到redis
            Map<String, Object> map = new ConcurrentHashMap<>();
            for(ChatListResponse response:responseList){
                map.put(response.getFriendId().toString(), response);
            }
            redisUtil.hmset(key, map, RedisConst.CHAT_LIST_KEY_TIMEOUT);
        }
    }
}
